package kyuuri.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TextNicoLiveData extends HttpServlet {
	private final static long serialVersionUID = 0;
	
	@Override
	protected void doGet(HttpServletRequest req, final HttpServletResponse resp) {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try {
			out = resp.getWriter();
			String text = "";

			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(NicoLive.class);
			query.setOrdering("pubDate");
			query.setFilter("broadcasting == true");
			try {
				List<NicoLive> results = (List<NicoLive>) query.execute("lives");
				if (results.iterator().hasNext()) {
					for (NicoLive live : results) {
						out.print(live.getGuid() + "|");
						out.print(live.getTitle() + "|");
						
						GregorianCalendar calendar = new GregorianCalendar();
						calendar.setTimeInMillis(calendar.getTimeInMillis() -
								                 live.getPubDate().getTime());
						int min = calendar.get(calendar.HOUR) * 60
						          + calendar.get(calendar.MINUTE);
						out.print(min + "|");
						out.println(live.getView());
					}
				}
			} finally {
				query.closeAll();
				out.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
